<template>
  <div class="login-container">
    <div class="login-form">
      <div class="logo-section">
        <h1>资源回收管理平台</h1>
      
      </div>
      
      <el-form 
        ref="loginFormRef" 
        :model="loginForm" 
        :rules="loginRules" 
        @submit.prevent="handleLogin"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            size="large"
            prefix-icon="User"
          />
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            size="large"
            prefix-icon="Lock"
            show-password
            @keyup.enter="handleLogin"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button 
            type="primary" 
            size="large" 
            :loading="loading" 
            @click="handleLogin"
            class="login-button"
          >
            {{ loading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>

        <el-form-item class="register-link">
          <span>还没有账号？</span>
          <el-link type="primary" @click="goToRegister">立即注册</el-link>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import { authAPI } from '@/api'

const router = useRouter()
const store = useStore()

// 响应式数据
const loading = ref(false)
const loginFormRef = ref(null)

// 登录表单
const loginForm = reactive({
  username: '',
  password: ''
})

// 表单验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ]
}

// 方法
const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  try {
    await loginFormRef.value.validate()
    loading.value = true
    
    const response = await authAPI.login({
      username: loginForm.username,
      password: loginForm.password
    })
    
    // 确保response有正确的数据结构
    if (!response || !response.user || !response.user.role) {
      console.error('Invalid response format:', response)
      throw new Error('登录响应数据格式错误')
    }
    
    // 保存用户信息和token到store
    store.commit('SET_USER', response.user)
    store.commit('SET_TOKEN', response.token)
    
    // 确保用户角色保存到localStorage
    localStorage.setItem('userRole', response.user.role)
    localStorage.setItem('userId', response.user.id)
    localStorage.setItem('userName', response.user.realName || response.user.username)
    
    ElMessage.success('登录成功')
    
    // 等待一小段时间确保状态已保存
    await new Promise(resolve => setTimeout(resolve, 100))
    
    // 根据用户角色跳转到对应页面
    const userRole = response.user.role
    switch (userRole) {
      case 'admin':
        await router.push('/admin')
        break
      case 'station_manager':
        await router.push('/station')
        break
      case 'customer':
        await router.push('/customer')
        break
      default:
        await router.push('/')
    }
  } catch (error) {
    console.error('Login error:', error)
    // 错误消息已经在拦截器中显示过了，这里不再重复显示
    // ElMessage.error(error.message || '登录失败，请检查用户名和密码')
  } finally {
    loading.value = false
  }
}

const goToRegister = () => {
  router.push('/register')
}
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.login-form {
  width: 100%;
  max-width: 400px;
  padding: 40px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
}

.logo-section {
  text-align: center;
  margin-bottom: 40px;
}

.logo-section h1 {
  margin: 0 0 10px 0;
  font-size: 28px;
  color: #333;
  font-weight: 600;
}

.logo-section p {
  margin: 0;
  font-size: 16px;
  color: #666;
}

.login-button {
  width: 100%;
  height: 44px;
  font-size: 18px;
  font-weight: 500;
}

.register-link {
  text-align: center;
  margin-bottom: 0;
}

.register-link span {
  margin-right: 8px;
  color: #666;
  font-size: 16px;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .login-container {
    padding: 10px;
  }
  
  .login-form {
    padding: 30px 20px;
  }
  
  .logo-section h1 {
    font-size: 24px;
  }
}
</style>
